package com.mygame.components

import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.component.Component
import com.almasb.fxgl.entity.state.StateComponent
import com.almasb.fxgl.pathfinding.astar.AStarMoveComponent
import com.mygame.Const
import kotlin.jvm.optionals.getOrNull

class CustomAIComponent : Component() {
    private lateinit var stateComponent: StateComponent
    private lateinit var astarMove: AStarMoveComponent
    private var tagEntity: Entity? = null
    override fun onAdded() {
        stateComponent = entity.getComponent(StateComponent::class.java)
        astarMove = entity.getComponent(AStarMoveComponent::class.java)
        tagEntity = entity.properties.getValueOptional<Entity>(Const.TAG_ENTITY).getOrNull()
    }

    override fun onUpdate(tpf: Double) {
        if (!entity.isActive) return
        tagEntity?.let {
            if (stateComponent.currentState == ATTACK) return
            // 将entity旋转到向量的方向
            entity.rotateToVector(it.center.subtract(entity.center))
            //if (!astarMove.isAtDestination) return//开放这个注释,是必须要到达指上一个追踪点之后,才会进行下一步追踪
            val cellX: Int = (it.center.x / Const.CELL_WIDTH).toInt()
            val cellY: Int = (it.center.y / Const.CELL_HEIGHT).toInt()
            val tagCell = try {
                astarMove.grid.get(cellX, cellY)
            } catch (e: ArrayIndexOutOfBoundsException) {//避免越界
                return
            }
            val currentCell = astarMove.currentCell.get()
            val distance = currentCell.distance(tagCell)//当前和追踪目标的格子距离,按1格2格算
            if (distance > 1) {//大于2格需要追踪
                stateComponent.changeState(RUN)
                astarMove.moveToCell(tagCell)
            } else {//停在2格当前的cell
                //println("plyer= ${it.center.x}, ${it.center.y}, enemy=${entity.center.x}, ${entity.center.y}")
                stateComponent.changeState(IDLE)
                astarMove.moveToCell(currentCell)
            }
        }
    }
}